package com.hlt.utils;

import com.github.houbb.sensitive.word.api.IWordAllow;
import com.github.houbb.sensitive.word.api.IWordDeny;
import com.github.houbb.sensitive.word.bs.SensitiveWordBs;
import com.github.houbb.sensitive.word.support.deny.WordDenys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;

/**
 * 敏感词过滤工具类
 */
@Component
public class SensitiveWordUtil {

    @Autowired
    private SensitiveWordBs sensitiveWordBs;

    @PostConstruct
    public void init() {

        WordDenys.chains(WordDenys.defaults(), new MyWordDeny());

        // 初始化敏感词库
        sensitiveWordBs = SensitiveWordBs.newInstance()
                .wordDeny(new MyWordDeny()) // 添加自定义敏感词
                .init();
    }

    /**
     * 判断文本是否包含敏感词
     * 
     * @param text 待检测文本
     * @return 是否包含敏感词
     */
    public boolean contains(String text) {
        if (text == null || text.trim().isEmpty()) {
            return false;
        }
        return sensitiveWordBs.contains(text);
    }

    /**
     * 获取文本中包含的所有敏感词
     * 
     * @param text 待检测文本
     * @return 敏感词列表
     */
    public List<String> findAll(String text) {
        if (text == null || text.trim().isEmpty()) {
            return List.of();
        }
        return sensitiveWordBs.findAll(text);
    }

    /**
     * 将文本中的敏感词替换为星号(*)
     * 
     * @param text 待处理文本
     * @return 处理后的文本
     */
    public String replace(String text) {
        if (text == null || text.trim().isEmpty()) {
            return text;
        }
        return sensitiveWordBs.replace(text);
    }
}